package com.itheima.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.mapper.CheckSetmealMapper;
import com.itheima.pojo.Setmeal;
import com.itheima.pojo.dto.CheckGroupDTO;
import com.itheima.service.CheckSetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CheckSetmealServiceImpl implements CheckSetmealService {
	@Autowired
	private CheckSetmealMapper checkSetmealMapper;
	@Autowired
	private ImageServiceImpl imageService;

	/**
	 * 新增套餐数据
	 *
	 * @param setmeal
	 * @param checkGroupIds
	 */
	@Override
	public void add(Setmeal setmeal, String checkGroupIds) {
		//插入套餐数据 并且获取套餐id
		checkSetmealMapper.insertSetmeal(setmeal);
		Integer setmealId = setmeal.getId();
		//插入套餐与检查组的关系
		String[] ids = checkGroupIds.split(",");
		for (String id : ids) {
			Integer SetmealGroupId = Integer.valueOf(id);
			checkSetmealMapper.insertAssociation(setmealId, SetmealGroupId);
		}
		//将图片插入redis缓存中的package中
		imageService.savePackageImages(setmeal.getImg());
	}

	/**
	 * 获取套餐数据
	 *
	 * @return
	 */
	@Override
	public List<Setmeal> getSetmeal() {
		List<Setmeal> list = checkSetmealMapper.getSetmeal();
		return list;
	}

	/**
	 * 根据套餐id查询套餐详情
	 *
	 * @param setmealId
	 * @return
	 */
	@Override
	public Setmeal findDetailById(Integer setmealId) {
		Setmeal setmeal = checkSetmealMapper.findDetailById(setmealId);
		return setmeal;
	}

	/**
	 * 根据id删除套餐
	 *
	 * @param id
	 */
	@Override
	public void delete(Integer id) {
		//查询删除对象的img路径
		Setmeal setmeal = checkSetmealMapper.findDetailById(id);
		//删除redis 和 OSS中的图片
		imageService.deleteImage(setmeal.getImg());
		//删除套餐与检查组的关系
		checkSetmealMapper.deleteAssociation(id);
		//删除套餐
		checkSetmealMapper.delete(id);

	}

	@Override
	public void edit(Setmeal setmeal, String checkGroupIds) {
		//更新关系表
		if (checkGroupIds != null && !checkGroupIds.equals("")) {
			//先删除原有的关系
			checkSetmealMapper.deleteAssociation(setmeal.getId());
			//创建新的关系
			String[] ids = checkGroupIds.split(",");
			for (String id : ids) {
				Integer checkGroupId = Integer.valueOf(id);
				checkSetmealMapper.insertAssociation(setmeal.getId(), checkGroupId);
			}
		}
		//更新套餐数据
		checkSetmealMapper.updateGroup(setmeal);
		//将图片插入redis缓存中的package中
		imageService.savePackageImages(setmeal.getImg());
	}

	@Override
	public PageResult findPage(QueryPageBean setmeal) {
		PageHelper.startPage(setmeal.getCurrentPage(), setmeal.getPageSize());
		Page<CheckGroupDTO> page = checkSetmealMapper.getPage(setmeal);
		return new PageResult(page.getTotal(), page.getResult());
	}
}
